import * as mongoose from 'mongoose';

type AutoPopulateSubsParam<T> = {
  schema: mongoose.Schema<T>;
  methods: Array<string>;
  path?: string;
  select?: string;
  populates?: Array<{
    path: string;
    select: string;
  }>;
};

const autoPopulateSubs = <T = any>({
  schema,
  methods,
  path,
  select,
  populates,
}: AutoPopulateSubsParam<T>): mongoose.Schema<T> => {
  methods.forEach((method: string) => {
    schema.pre(method, function (next) {
      const ctx = this as any;
      if (Array.isArray(populates)) {
        populates.forEach((populateItem) => {
          ctx.populate({
            path: populateItem.path,
            select: populateItem.select,
          });
        });
      } else if (path && select) {
        ctx.populate({
          path,
          select,
        });
      }
      next();
    });
  });

  return schema;
};

export default autoPopulateSubs;
